from typing import Any

from django.core.files.uploadedfile import InMemoryUploadedFile
from rest_framework import serializers

from .models import Movie


class MovieSerializer(serializers.ModelSerializer):
    """电影序列化器类"""

    class Meta:
        model = Movie  # 关联的模型
        fields = ["id", "title", "genres"]  # 序列化的字段


class PreferencesDetailSerializer(serializers.Serializer):
    """偏好详情序列化器类"""

    genre = serializers.CharField(max_length=100, allow_blank=True, required=False, help_text="类型")
    director = serializers.CharField(max_length=100, allow_blank=True, required=False, help_text="导演")
    actor = serializers.CharField(max_length=100, allow_blank=True, required=False, help_text="演员")
    year = serializers.IntegerField(
        min_value=1900, max_value=2099, required=False, allow_null=False, help_text="年份"
    )

    def validate(self, data: dict[str, Any]) -> dict[str, Any]:
        """验证偏好数据"""
        # 检查所有字段是否都为空或未提供
        if all(value in [None, ""] for value in data.values()):
            raise serializers.ValidationError(
                "至少需要提供一个偏好设置"
            )
        return data


class AddPreferenceSerializer(serializers.Serializer):
    """添加偏好序列化器类"""

    new_preferences = PreferencesDetailSerializer()


class PreferencesSerializer(serializers.Serializer):
    """偏好序列化器类"""

    genre = serializers.ListField(child=serializers.CharField(), required=False, help_text="类型列表")
    director = serializers.ListField(child=serializers.CharField(), required=False, help_text="导演列表")
    actor = serializers.ListField(child=serializers.CharField(), required=False, help_text="演员列表")
    year = serializers.ListField(child=serializers.CharField(), required=False, help_text="年份列表")


class AddToWatchHistorySerializer(serializers.Serializer):
    """添加到观看历史序列化器类"""

    id = serializers.IntegerField()

    def validate_id(self, value: int) -> int:
        """
        验证电影ID是否存在
        """
        try:
            Movie.objects.get(id=value)
        except Movie.DoesNotExist:
            raise serializers.ValidationError("无效的电影ID，该电影不存在")
        return value


class WatchHistorySerializer(serializers.Serializer):
    """观看历史序列化器类"""

    title = serializers.CharField(max_length=255, help_text="标题")
    year = serializers.IntegerField(help_text="年份")
    director = serializers.CharField(max_length=255, help_text="导演")
    genre = serializers.CharField(max_length=255, help_text="类型")


class GeneralFileUploadSerializer(serializers.Serializer):
    """通用文件上传序列化器类"""

    file = serializers.FileField()

    def validate_file(self, value: InMemoryUploadedFile) -> InMemoryUploadedFile:
        """验证上传文件"""
        # 验证文件大小（例如，限制为10MB）
        if value.size > 10485760:
            raise serializers.ValidationError(
                "文件大小超过10MB限制"
            )

        # 验证文件MIME类型
        allowed_types = ["text/csv", "application/json", "application/xml"]
        if value.content_type not in allowed_types:
            raise serializers.ValidationError("不支持的文件类型")

        return value
